import {
  Button,
  Form,
  Input,
  Popconfirm,
  Radio,
  Space,
  Switch,
  Tag,
} from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import CommonPage from "@/components/page/CommonPage";

import styled from "styled-components";
import Add from "@/components/svg/action-slot-icon/Add";
import CrudTable from "@/components/table/CrudTable";
import QueryBarItem from "@/components/query-bar/QueryBarItem";
import { useEffect, useRef, useState } from "react";
import useGetState from "@/hooks/useGetState";
import useCRUD from "@/hooks/useCRUD";
import {
  deleteResource,
  getResources,
  saveOrUpdateResource,
  updateResourceAnonymous,
} from "@/api/resource";
import { formatDate } from "@/utils/common/common";
import useMyContext from "@/hooks/useContext";
import CrudModal from "@/components/table/CrudModal";
const Styled = styled.div``;

// 请求方法
const requestMethods = ["GET", "POST", "DELETE", "PUT"];

// 请求方法对应不同类型的标签 (计算属性传参)
function tagType(type) {
  switch (type) {
    case "GET":
      return "processing";
    case "POST":
      return "success";
    case "PUT":
      return "warning";
    case "DELETE":
      return "error";
    default:
      return "processing";
  }
}
const Resource = () => {
  const { messageApi } = useMyContext();
  const $table = useRef();
  //搜索框参数
  const [queryItems, setQueryItems, getQueryItems] = useGetState({});
  //所有switch的状态loading管理
  const [loadingStates, setLoadingStates] = useState({});
  const {
    modalVisible,
    setModalVisible,
    modalTitle,
    modalLoading,
    handleAdd,
    handleDelete,
    handleEdit,
    handleSave,
    modalForm,
    setModalForm,
    modalFormRef,
    clearFormFields,
    modalAction,
    setModalAction,
  } = useCRUD({
    name: "接口",
    doCreate: saveOrUpdateResource,
    doDelete: deleteResource,
    doUpdate: saveOrUpdateResource,
    refresh: () => $table.current?.handleSearch(),
  });
  const columns = [
    {
      title: "资源名称",
      key: "name",
      width: 80,
      ellipsis: { showTitle: true },
      render(_, record, index) {
        return <>{record.name}</>;
      },
    },
    {
      title: "资源路径",
      key: "url",
      width: 100,
      ellipsis: { showTitle: true },
      render(_, record, index) {
        return <>{record.url}</>;
      },
    },
    {
      title: "请求方式",
      key: "request_method",
      width: 50,
      align: "center",
      render(_, record, index) {
        return (
          <>
            {record.children ? (
              ""
            ) : (
              <Tag color={tagType(record.request_method)}>
                {record.request_method}
              </Tag>
            )}
          </>
        );
      },
    },
    {
      title: "匿名访问",
      key: "is_hidden",
      width: 50,
      align: "center",
      render(_, record, index) {
        //自由一级目录的子模块才可以匿名访问
        return (
          <>
            {record.children ? (
              ""
            ) : (
              <Switch
                size="small"
                checked={record.is_anonymous}
                loading={!!loadingStates[record.id]}
                onClick={(bol) => {
                  handleUpdateAnonymous(record);
                }}
              />
            )}
          </>
        );
      },
    },
    {
      title: "创建日期",
      key: "created_at",
      width: 60,
      render(_, record, index) {
        return <span>{formatDate(record.created_at)}</span>;
      },
    },
    {
      title: "操作",
      key: "actions",
      width: 115,
      align: "center",
      fixed: "right",
      render(_, record, index) {
        return (
          <>
            <Button
              type="link"
              style={{
                marginRight: "5px",
                color: "green",
                display: `${record.children ? "" : "none"}`, //一级模块才允许新增
              }}
              icon={<PlusOutlined />}
              onClick={() => {
                handleAdd(); // 弹窗显示
                //设置新接口的父接口
                setModalForm({
                  ...modalForm,
                  parent_id: record.id,
                });
              }}
            >
              新增
            </Button>
            <Button
              type="link"
              style={{ marginRight: "5px" }}
              icon={<EditOutlined />}
              onClick={() => {
                //根据子项选择打开不同的弹窗修改数据
                record.children ? handleEditModule(record) : handleEdit(record);
              }}
            >
              编辑
            </Button>
            <Popconfirm
              title="确认删除该资源吗"
              onConfirm={() => {
                handleDelete(record.id);
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="link"
                icon={<DeleteOutlined />}
                style={{ color: "#D03050FF" }}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  function updateQueryItems(newQueryItems) {
    setQueryItems(newQueryItems);
  }
  // 修改是否允许匿名访问
  async function handleUpdateAnonymous(row) {
    if (!row.id) return;
    setLoadingStates({
      ...loadingStates,
      [row.id]: true,
    });
    row.is_anonymous = row.is_anonymous === 0 ? 1 : 0;
    await updateResourceAnonymous(row);
    setLoadingStates({
      ...loadingStates,
      [row.id]: false,
    });
    messageApi.success(row.is_anonymous ? "已允许匿名访问" : "已禁止匿名访问");
  }

  // 添加模块
  const [moduleModalVisible, setModuleModalVisible] = useState(false);

  async function handleAddModule() {
    setModalAction("add");
    setModalForm({});
    setModuleModalVisible(true);
  }

  function handleEditModule(row) {
    setModalAction("edit");
    setModalForm({ ...row });
    setModuleModalVisible(true);
  }

  async function handleModuleSave() {
    handleSave();
    setModuleModalVisible(false);
  }

  useEffect(() => {
    $table.current.handleSearch();
  }, []);

  return (
    <Styled>
      <CommonPage title="接口管理">
        <div className="action-slot" slot="action">
          <Button type="primary" icon={<Add />} onClick={handleAddModule}>
            新增模块
          </Button>
        </div>

        <CrudTable
          ref={$table}
          columns={columns}
          queryItems={queryItems}
          updateQueryItems={updateQueryItems}
          getQueryItems={getQueryItems}
          singleLine={true}
          getData={getResources}
          hasRowSelection={false}
        >
          <div className="queryBar-slot flex label-ml-15" slot="queryBar">
            <QueryBarItem label="资源名" labelWidth={50}>
              <Input
                placeholder="请输入资源名"
                allowClear
                value={queryItems.keyword}
                onChange={(e) => {
                  setQueryItems({
                    ...queryItems,
                    keyword: e.target.value,
                  });
                }}
              />
            </QueryBarItem>
          </div>
        </CrudTable>

        {/* 接口添加弹窗 */}
        <CrudModal
          visible={modalVisible}
          setModalVisible={setModalVisible}
          loading={modalLoading}
          title={modalTitle}
          handleSave={handleSave}
          clearFormFields={clearFormFields}
        >
          <Form
            form={modalFormRef}
            name="add-interface"
            labelAlign="left"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item label="资源名" name="name">
              <Input
                placeholder="请输入资源名"
                value={modalForm.name}
                onChange={(e) => {
                  setModalForm({
                    ...modalForm,
                    name: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item label="资源路径" name="url">
              <Input
                placeholder="请输入资源路径"
                value={modalForm.url}
                onChange={(e) => {
                  setModalForm({
                    ...modalForm,
                    url: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item label="请求方式" name="request_method">
              <Radio.Group
                name="radiogroup"
                value={modalForm.request_method}
                onChange={(e) => {
                  // e.target.value对应每一个radio的value值
                  setModalForm({
                    ...modalForm,
                    request_method: e.target.value,
                  });
                }}
              >
                <Space size="large">
                  {requestMethods.map((item) => {
                    return (
                      <Radio key={item} value={item}>
                        <Tag color={tagType(item)}>{item}</Tag>
                      </Radio>
                    );
                  })}
                </Space>
              </Radio.Group>
            </Form.Item>
          </Form>
        </CrudModal>

        {/* 模块添加弹窗 */}
        <CrudModal
          visible={moduleModalVisible}
          setModalVisible={setModuleModalVisible}
          title={`${modalAction === "add" ? "新增" : "编辑"}模块`}
          loading={modalVisible}
          handleSave={handleModuleSave}
          clearFormFields={clearFormFields}
        >
          <Form
            name="module"
            ref={modalFormRef}
            labelAlign="left"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item label="模块名" name="name">
              <Input
                placeholder="请输入模块名"
                value={modalForm.name}
                onChange={(e) => {
                  setModalForm({
                    ...modalForm,
                    name: e.target.value,
                  });
                }}
              />
            </Form.Item>
          </Form>
        </CrudModal>
      </CommonPage>
    </Styled>
  );
};

export default Resource;
